package seatiger.tomcat.util.http;

import seatiger.tomcat.util.buf.MessageBytes;

/**
 * 对报文头的封装
 */
public class MimeHeaders {

    public static final int DEFAULT_HEADER_SIZE = 8;

    private int count;

    //默认存储8个报文头
    private MimeHeaderField[] headers = new MimeHeaderField[DEFAULT_HEADER_SIZE];

    /**
     * 创建一个新的报文头对象
     *
     * @param b
     * @param startN
     * @param len
     * @return
     */
    public MessageBytes addValue(byte[] b, int startN, int len) {
        MimeHeaderField mhf = createHeader();
        mhf.getName().setBytes(b, startN, len);
        return mhf.getValue();
    }

    private MimeHeaderField createHeader() {
        MimeHeaderField mh;
        int len = headers.length;
        //扩容
        if (count >= len) {
            MimeHeaderField tmp[] = new MimeHeaderField[count * 2];
            System.arraycopy(headers, 0, tmp, 0, len);
            headers = tmp;
        }
        if ((mh = headers[count]) == null) {
            headers[count] = mh = new MimeHeaderField();
        }
        count++;
        return mh;
    }

    @Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        for (MimeHeaderField field : headers) {
            buffer.append(field.getName());
            buffer.append(":");
            buffer.append(field.getValue());
            buffer.append("\n");
        }
        return buffer.toString();
    }

    public void recycle() {
        clear();
    }

    public void clear() {
        for (int i = 0; i < count; i++) {
            headers[i].recycle();
        }
        count = 0;
    }

    public String getHeader(String name) {
        MessageBytes value = getValue(name);
        return value == null ? null : value.toString();
    }

    public MessageBytes getValue(String name) {
        for (int i = 0; i < count;i++){
            if (headers[i].getName().toString().equals(name)) {
                return headers[i].getValue();
            }
        }
        return null;
    }
}

class MimeHeaderField {
    protected final MessageBytes nameB = new MessageBytes();
    protected final MessageBytes valueB = new MessageBytes();

    public void recycle() {
        nameB.recycle();
        valueB.recycle();
    }

    public MessageBytes getName() {
        return nameB;
    }

    public MessageBytes getValue() {
        return valueB;
    }
}
